package com.bit.demo.springcatpchademo.controller;

import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import com.bit.demo.springcatpchademo.model.CatpchaInfo;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/catpcha")
@RestController
public class CatpchaController {
    @Autowired
    private CatpchaInfo catpchaInfo;
    private final static Long VALID_TIME=20*60*1000L;
    /**
     * 获取验证码
     * @param response 响应对象
     * @param session 会话对象
     * @throws IOException
     */
    @RequestMapping("/getCatpcha")
    public void getCatpcha(HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");

        ICaptcha captcha = new LineCaptcha(catpchaInfo.getWidth(), catpchaInfo.getHeight());
        String code=captcha.getCode();
        session.setAttribute(catpchaInfo.getSession().getKey(),code);
        session.setAttribute(catpchaInfo.getSession().getDate(),new Date());
        captcha.write(response.getOutputStream());
    }

    /**
     * 校验验证码是否正确
     * @param captcha 用户输入的验证码
     * @param session
     * @return true:校验成功 false:校验失败
     */
    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session) {
        if(!StringUtils.hasLength(captcha)) {
            return false;
        }
        String code=(String)session.getAttribute(catpchaInfo.getSession().getKey());
        Date date=(Date)session.getAttribute(catpchaInfo.getSession().getDate());
        if(captcha.equalsIgnoreCase(code) && date!=null
                && System.currentTimeMillis()-date.getTime()<VALID_TIME) {
            return true;
        }
        return false;
    }
}
